package com.mt.repair.service.repairManagement.impl;

import com.mt.common.core.web.JsonResult;
import com.mt.common.system.entity.User;
import com.mt.common.system.service.UserService;
import com.mt.repair.dao.repairManagement.NoticeCatUserDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.repair.entity.repairManagement.NoticeCatUser;
import com.mt.repair.service.repairManagement.NoticeCatUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class NoticeCatUserServiceBean extends BaseService implements NoticeCatUserService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private NoticeCatUserDao noticeCatUserDao;

	@Resource
	private RedisTemplate<String, List<NoticeCatUser>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询维修评价集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findNoticeCatUsers(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindNoticeCatUsers(pageDTO);
		List<NoticeCatUser> noticeCatUserDTOS = this.noticeCatUserDao.findNoticeCatUsers(pageDTO);
		Long totalCount = this.noticeCatUserDao.findNoticeCatUserTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(noticeCatUserDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部维修评价集合
	 *
	 */
	@Override
	public List<NoticeCatUser> findAllNoticeCatUsers(){
		return this.noticeCatUserDao.findAllNoticeCatUsers();
	}

	/**
	 * 查询所有维修评价集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<NoticeCatUser> findAllNoticeCatUsersWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllNoticeCatUsersWithIdName();
		return this.noticeCatUserDao.findAllNoticeCatUsersWithIdName();
	}

	/**
	 * 根据名称查询维修评价集合(只提取ID 和 Name)
	 *
	 * @param noticeCatUserName 名称
	 */
	@Override
	public List<NoticeCatUser> findNoticeCatUsersWithIdNameByName(String noticeCatUserName){
		//TODO:请在此校验参数的合法性
		this.validateFindNoticeCatUsersWithIdNameByName(noticeCatUserName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:NoticeCatUser_where_noticeCatUserName_" + noticeCatUserName);
		List<NoticeCatUser> noticeCatUsers = new ArrayList<>();
		if (keys.isEmpty()) {
		noticeCatUsers = this.noticeCatUserDao.findNoticeCatUsersWithIdNameByName(noticeCatUserName);
		redisTemplate.opsForValue().set("searchData:NoticeCatUser_where_noticeCatUserName_" + noticeCatUserName, noticeCatUsers, 30, TimeUnit.DAYS);
		} else {
		noticeCatUsers = redisTemplate.opsForValue().get("searchData:NoticeCatUser_where_noticeCatUserName_" + noticeCatUserName);
		}
		return noticeCatUsers;
	}

	/**
	 * 根据ID查询指定的维修评价(只提取ID 和 Name)
	 *
	 * @param noticeCatUserId Id
	 */
	@Override
	public NoticeCatUser findNoticeCatUsersWithIdNameById(Long noticeCatUserId){
		//TODO:请在此校验参数的合法性
		this.validateFindNoticeCatUsersWithIdNameById(noticeCatUserId);
		return this.noticeCatUserDao.findNoticeCatUsersWithIdNameById(noticeCatUserId);
	}

	/**
	 * 根据ID查询指定的维修评价
	 *
	 * @param noticeCatUserId Id
	 */
	@Override
	public NoticeCatUser findNoticeCatUser(Long noticeCatUserId){
		//TODO:请在此校验参数的合法性
		this.validateFindNoticeCatUser(noticeCatUserId);
		return this.noticeCatUserDao.findNoticeCatUser(noticeCatUserId);
	}

	/**
	 * 根据ID查询指定的维修评价(包含外键)
	 *
	 * @param noticeCatUserId Id
	 */
	@Override
	public NoticeCatUser findNoticeCatUserWithForeignName(Long noticeCatUserId){
		//TODO:请在此校验参数的合法性
		this.validateFindNoticeCatUserWithForeignName(noticeCatUserId);
		return this.noticeCatUserDao.findNoticeCatUserWithForeignName(noticeCatUserId);
	}

	/**
	 * 新增维修评价
	 *
	 * @param noticeCatUser 实体对象
	 */
	@Override
	public NoticeCatUser saveNoticeCatUser(NoticeCatUser noticeCatUser){
		//TODO:请在此校验参数的合法性
		this.validateSaveNoticeCatUser(noticeCatUser);
		//TODO:填充公共参数
		this.setSavePulicColumns(noticeCatUser);
		Long rows = this.noticeCatUserDao.saveNoticeCatUser(noticeCatUser);
		if(rows != 1)
		{
			String error = "新增保存维修评价出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return noticeCatUser;
	}

	/**
	 * 更新维修评价
	 *
	 * @param noticeCatUser 实体对象
	 */
	@Override
	public NoticeCatUser updateNoticeCatUser(NoticeCatUser noticeCatUser){
		//TODO:请在此校验参数的合法性
		this.validateUpdateNoticeCatUser(noticeCatUser);
		Long rows = this.noticeCatUserDao.updateNoticeCatUser(noticeCatUser);
		if(rows != 1)
		{
			String error = "修改保存维修评价出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return noticeCatUser;
	}

	/**
	 * 根据ID删除维修评价
	 *
	 * @param noticeCatUserId ID
	 */
	@Override
	public void deleteNoticeCatUser(Long noticeCatUserId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteNoticeCatUser(noticeCatUserId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(NoticeCatUser.class, noticeCatUserId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.noticeCatUserDao.deleteNoticeCatUser(noticeCatUserId);
		if(rows != 1){
			String error = "删除维修评价出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}
	@Autowired
	private UserService userService;
	@Override
	public JsonResult generate(Long noticeId, String noticeType, String selectedString) {
		List<NoticeCatUser>  list=new ArrayList<>();
		if("部分".equals(noticeType)){
			String[] userIds = selectedString.split(",");
			for (int i = 0; i < userIds.length; i++) {
				NoticeCatUser noticeCatUser = new NoticeCatUser();
				noticeCatUser.setNoticeId(noticeId);
				noticeCatUser.setUserId(Long.valueOf(userIds[i]));
				noticeCatUser.setReadStatus(1);
				list.add(noticeCatUser);
			}
		}

		else if("角色".equals(noticeType)){
			//根据角色查询用户、
			String[] roleIds=selectedString.split(",");
			List<Long> roleIdList=new ArrayList<>();
			for (int i = 0; i < roleIds.length; i++) {
				roleIdList.add(Long.valueOf(roleIds[i]));
			}
			List<User> users = userService.getUserIdByRoleId(roleIdList);
			users.forEach(user -> {
				NoticeCatUser noticeCatUser = new NoticeCatUser();
				noticeCatUser.setNoticeId(noticeId);
				noticeCatUser.setUserId(Long.valueOf(user.getEid()));
				noticeCatUser.setReadStatus(1);
				list.add(noticeCatUser);
			});
		}else{
			//查询所有用户
			List<User> users = userService.listAll(new HashMap<>());
			users.forEach(user -> {
				NoticeCatUser noticeCatUser = new NoticeCatUser();
				noticeCatUser.setNoticeId(noticeId);
				noticeCatUser.setUserId(Long.valueOf(user.getEid()));
				noticeCatUser.setReadStatus(1);
				list.add(noticeCatUser);
			});
		}
		list.forEach(noticeCatUser -> {
			this.setSavePulicColumns(noticeCatUser);
			this.noticeCatUserDao.saveNoticeCatUser(noticeCatUser);
		});
		return JsonResult.ok("新增成功");
	}

	//TODO:---------------验证-------------------

	private void validateFindNoticeCatUsers(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateNoticeCatUser()写法
	}

	private void validateFindNoticeCatUsersWithIdNameByName(String noticeCatUserName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateNoticeCatUser()写法
	}


	private void validateFindAllNoticeCatUsersWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateNoticeCatUser()写法
	}

	private void validateFindNoticeCatUsersWithIdNameById(Long noticeCatUserId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateNoticeCatUser()写法
	}

	private void validateFindNoticeCatUser(Long noticeCatUserId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateNoticeCatUser()写法
	}

	private void validateFindNoticeCatUserWithForeignName(Long noticeCatUserId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateNoticeCatUser()写法
	}

	private void validateSaveNoticeCatUser(NoticeCatUser noticeCatUser) {
	//不为空判断
	if (noticeCatUser.getEid() != null || noticeCatUser.getCreatorId() != null || noticeCatUser.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateNoticeCatUser()写法
	}

	private void validateUpdateNoticeCatUser(NoticeCatUser noticeCatUser) {
	//不为空判断
	if (noticeCatUser.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.noticeCatUserDao.findNoticeCatUserTotalCount(PageDTO.create(NoticeCatUser.FIELD_ID, noticeCatUser.getEid())) == 0) {
	throw new BusinessException("修改的维修评价 " + noticeCatUser.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateNoticeCatUser()写法
	}

	private void validateDeleteNoticeCatUser(Long noticeCatUserId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateNoticeCatUser()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
